import React, {useState} from "react";
import {Form, Input, Modal, Switch} from "antd";
import {addCategoryUrl, editCategoryUrl} from "@/api/blog/category.ts";
import {globalMessageApi} from "@/components/OpComponent/Message";


export default React.forwardRef((props: any, ref: any) => {
    const {
        getList
    } = props
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalEdit, setIsModalEdit] = useState(false)


    const [form] = Form.useForm()
    const [formValues, setFormValues] = useState<any>();


    const handleOk = () => {
        // 进行校验
        if (!form) return
        form.validateFields().then((values) => {
            if (formValues.bcId) {
                return editCategoryUrl({
                    ...values,
                    bcId: formValues.bcId
                }).then((res) => {
                    globalMessageApi.success(res.msg)
                    getList()
                    setIsModalOpen(false);
                })
            } else {
                addCategoryUrl(values).then((res) => {
                    globalMessageApi.success(res.msg)
                    getList()
                    setIsModalOpen(false);
                })
            }
        })
    };


    const handleCancel = () => {
        setIsModalOpen(false);
    }

    const openModal = (data = {bcId: null}) => {
        setFormValues(data)
        if (data && data.bcId) {
            form.setFieldsValue(data)
            setIsModalEdit(true)
            // 获取详情
            setIsModalOpen(true)
        } else {
            setIsModalEdit(false)
            setIsModalOpen(true)
        }
    }

    React.useImperativeHandle(ref, () => ({
        openModal: openModal
    }))
    return <Modal title={isModalEdit ? "编辑专栏信息" : "新增专栏信息"}
                  open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
                  modalRender={(dom) => (
                      <Form form={form} initialValues={formValues}>
                          {dom}
                      </Form>
                  )}
    >
        <Form.Item name={"bcName"} label="专栏名称"
                   rules={[{required: true, message: '专栏名称不能为空!'}]}>
            <Input placeholder="请输入专栏名称"/>
        </Form.Item>
        <Form.Item name={"sort"} label="专栏排序" rules={[{required: true, message: '专栏排序不能为空!'}]}>
            <Input type="number" placeholder="请输入专栏序号"/>
        </Form.Item>
        <Form.Item name={"status"} label="专栏状态" rules={[{required: true, message: '专栏状态不能为空!'}]}>
            <Switch/>
        </Form.Item>
    </Modal>
})
